package com.hm.interceptor;

import com.hm.utils.JwtUtil;
import com.hm.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    // 创建登录拦截器

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("--------开始执行--------preHandle----------------");
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            response.setStatus(401);
            return false;
        }
        try {
            // 解析token是否成功
            Map<String, Object> claims = JwtUtil.parseToken(authorization);
            // 把数据存储到ThreadLocal
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        } finally {
            log.info("--------结束执行--------preHandle----------------");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("--------开始执行--------afterCompletion----------------");
        ThreadLocalUtil.remove();
        log.info("--------结束执行--------afterCompletion----------------");
    }
}
